import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Form,
  Input,
  DatePicker,
  Select,
  Button,
  Card,
  Radio,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import * as option from '../../../common/options';
import moment from 'moment';
import router from 'umi/router';

const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;
const RadioGroup = Radio.Group;

@connect(({ loading }) => ({
  submitting: loading.effects['form/submitRegularForm'],
}))
@Form.create()
class createForm extends PureComponent {
  handleSubmit = e => {
    let _this = this;
    const { dispatch, form, location: { query } } = this.props;
    e.preventDefault();
    form.validateFieldsAndScroll((err, values) => {

      if (values.type === 1) {
        values.expire = moment(values.expire).format('YYYY-MM-DD');
      } else {
        values.expire = values.expire;
      }

      // values.minRule = Number(values.minRule);
      // values.sendMode = 1;
      if (values.multipleSelect.indexOf(3) !== -1) {
        values.normal = 1;
      } else {
        values.normal = 0;
      }
      if (values.multipleSelect.indexOf(2) !== -1) {
        values.hot = 1;
      } else {
        values.hot = 0;
      }
      if (values.multipleSelect.indexOf(1) !== -1) {
        values.newHand = 1;
      } else {
        values.newHand = 0;
      }
      delete values.multipleSelect;
      if (!err) {
        if (!query.couponNo) {
          dispatch({
            type: 'Coupon/add',
            payload: values,
            callback(res) {
              if (res.code === 200) {
                _this.props.history.goBack();
              }

            },
          });
        } else {
          values.couponNo = query.couponNo;
          dispatch({
            type: 'Coupon/update',
            payload: values,
            callback() {
              _this.props.history.goBack();
            },
          });
        }
      }
    });
  };

  constructor(props) {
    super(props);
    this.state = {
      values: {},
      startValue: null,
      endValue: null,
    };
  }

  componentWillMount() {
    const { dispatch, location: { query } } = this.props;
    let _this = this;
    if (query.couponNo) {
      dispatch({
        type: 'Coupon/getDesc',
        payload: { CouponNo: query.couponNo },
        callback(res) {
          if (res.code === 200) {
            res.msg.startTime = moment(res.msg.startTime).format('YYYY-MM-DD');
            res.msg.endTime = moment(res.msg.endTime).format('YYYY-MM-DD');

            _this.setState({
              values: res.msg,
            });
          }
        },
      });
    }
  }


  onChange = (field, value) => {
    this.setState({
      [field]: value,
    });
  };

  onEndChange = (value) => {
    this.onChange('endValue', value);
  };


  render() {
    const { submitting } = this.props;
    const { values } = this.state;
    const {
      form: { getFieldDecorator, getFieldValue },
    } = this.props;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };
    const goBack = () => {
      this.props.history.goBack();
    };
    const selectOption = [<Option value={1} key={1}>新手标</Option>,
      <Option value={2} key={2}>hot标</Option>,
      <Option value={3} key={3}>普通标</Option>];
    values.multipleSelect = [];
    if (values.normal === 1) {
      values.multipleSelect.push(3);
    }
    if (values.hot === 1) {
      values.multipleSelect.push(2);
    }
    if (values.newHand === 1) {
      values.multipleSelect.push(1);
    }
    const maxValue = (rule, value, callback) => {
      if (value > 100) {
        callback('请输入小于100%的数值!');
      }
      if (parseInt(value) !== Number(value) && value.toString().split('.')[1].length > 1) {
        callback('只能输入一位小数!');

      }
      callback();
    };

    return (
      values ?
        <PageHeaderWrapper
          title='新建优惠券'
        >
          <Card bordered={false}>
            <Form onSubmit={this.handleSubmit} style={{ marginTop: 8 }}>
              <FormItem {...formItemLayout} label='优惠券名称'>
                {getFieldDecorator('couponName', {
                  rules: [{ required: true, message: '请填写优惠券名称' }],
                  initialValue: values.couponName,
                })(<Input placeholder='请填写优惠券名称'/>)}
              </FormItem>
              <FormItem {...formItemLayout} label='优惠券类型'>
                {getFieldDecorator('couponType', {
                  rules: [
                    {
                      required: true,
                      message: '请选择优惠券类型',

                    },
                  ],
                  initialValue: values.couponType,

                })(
                  <Select placeholder='请选择优惠券类型' style={{ width: '100%' }}>
                    {option.couponType.map((item) => {
                      return (<Option value={item.key} key={item.key}>{item.value}</Option>);
                    })}
                  </Select>,
                )}
              </FormItem>

              <FormItem {...formItemLayout} label={getFieldValue('couponType') === 3 ? '优惠券面值(%)' : '优惠券面值(元)'}>
                {getFieldDecorator('couponValue', {
                  rules: [
                    {
                      required: true,
                      message: '请填写优惠券面值！',
                    },
                    getFieldValue('couponType') === 3 ? { validator: maxValue } : '',

                  ], initialValue: values.couponValue,
                })(<Input type={'Number'} placeholder='请填写优惠券面值'/>)}
              </FormItem>

              {
                getFieldValue('couponType') === 1 || getFieldValue('couponType') === 2 ? [
                  <FormItem {...formItemLayout} label='使用下限(元)'>
                    {getFieldDecorator('minRule', {
                      rules: [
                        {
                          required: true,
                          message: '请填写使用下限',
                        },
                      ],
                      initialValue: values.minRule,

                    })(<Input type={'Number'} placeholder='请填写使用下限'/>)}
                  </FormItem>,
                ] : ''
              }

              <FormItem {...formItemLayout} label='适用标的'>
                {getFieldDecorator('multipleSelect', {
                  rules: [
                    { required: true, message: '请选择适用标的' },
                  ],
                  initialValue: values.multipleSelect.length > 0 ? values.multipleSelect : [3],
                })(
                  <Select mode="multiple" placeholder='请选择适用标的' style={{ width: '100%' }}>
                    {selectOption}
                  </Select>,
                )}
              </FormItem>

              <FormItem {...formItemLayout} label='有效期(单选)'>
                {getFieldDecorator('type', {
                  rules: [
                    {
                      required: true,
                      message: '请选择有效期',
                    },
                  ],
                  initialValue: values.type || 1,

                })(
                  <RadioGroup>
                    <Radio value={1} key={1}> 到期日</Radio>
                    <Radio value={2} key={2}> 有效期</Radio>
                  </RadioGroup>,
                )}
              </FormItem>
              {
                getFieldValue('type') === 1 ?
                  <FormItem {...formItemLayout} label='到期日期'>
                    {getFieldDecorator('expire', {
                      rules: [
                        { required: true, message: '请选择到期日期' },
                      ],
                      initialValue: moment(values.expire),
                    })(
                      <DatePicker
                        placeholder="请选择到期日期"
                        onChange={this.onEndChange}
                        style={{ width: '100%' }}/>,
                    )}
                  </FormItem>
                  : <FormItem {...formItemLayout} label={'发放日起(天)'}>
                    {getFieldDecorator('expire', {
                      rules: [
                        {
                          required: true,
                          message: '请填写有效天数！',
                        },
                      ], initialValue: values.expire,
                    })(<Input type={'Number'} placeholder='请填写有效天数'/>)}
                  </FormItem>
              }


              <FormItem {...formItemLayout} label='备注'>
                {getFieldDecorator('remark', {
                  rules: [{ required: false, message: '请填写备注' }],
                  initialValue: values.remark,
                })(
                  <TextArea
                    style={{ minHeight: 32 }}
                    placeholder='请填写备注'
                    rows={4}
                  />,
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='状态'>
                {getFieldDecorator('status', {
                  rules: [{ required: true, message: '请选择状态' }],
                  initialValue: values.status || 1,
                })(
                  <RadioGroup>
                    <Radio value={1} key={1}>启用</Radio>
                    <Radio value={2} key={2}>停用</Radio>
                  </RadioGroup>,
                )}
              </FormItem>
              <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
                <Button loading={submitting} onClick={() => goBack()} style={{ marginRight: '20px' }}>
                  返回
                </Button>

                <Button type="primary" htmlType="submit" loading={submitting}>
                  提交
                </Button>

              </FormItem>
            </Form>
          </Card>
        </PageHeaderWrapper>
        : ''

    );
  }
}

export default createForm;
